package com.heima.leadnews.user.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.ApUserDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.leadnews.user.mapper.ApUserMapper;
import com.heima.leadnews.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(ApUserDto dto) {
        //1.判断是游客登录还是用户登录
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            //如果不为空,用户登录,查询数据库
            LambdaQueryWrapper<ApUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser user = this.getOne(lambdaQueryWrapper);

            //判断是否存在
            if (user == null)
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST); //不存在,抛出异常


            //存在,判断密码是否正确
            String md5 = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
            if (!md5.equals(user.getPassword()))
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR); //不相等,抛异常

            //相等,登录成功,将token和数据响应给前端
            String token = AppJwtUtil.getToken(user.getId().longValue());
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            user.setPassword(null);
            user.setSalt(null);
            data.put("user", user);
            return ResponseResult.okResult(data);
        }
        //游客登录
        String token = AppJwtUtil.getToken(0L);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
